package main

import (
	"CampusNetworkTools/config"
	"CampusNetworkTools/core"
	"CampusNetworkTools/win_bridge"
	"CampusNetworkTools/win_bridge/wifi"
	"embed"
	"github.com/electricbubble/go-toast"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"io"
	"os"
	"strings"
)

//go:embed all:frontend/dist
var assets embed.FS

//go:embed build/appicon.png
var appIcon []byte

func containsSsid(ssids []string, ssid string) bool {
	for _, s := range ssids {
		ok := strings.Contains(s, ssid)
		if ok {
			return true
		}
	}

	return false
}

func main() {
	log.SetFormatter(&log.TextFormatter{DisableQuote: true, TimestampFormat: "2006-01-02 15:04:05"})
	file, err := os.OpenFile(config.ExeDir()+"/app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err == nil {
		log.SetOutput(io.MultiWriter(file, os.Stdout))
	} else {
		log.Info("Failed to log to file, using default stderr")
	}

	err = config.InitConfig()
	if err != nil {
		log.Fatalln(errors.WithMessage(err, "初始化配置文件"))
	}

	app := NewApp()

	if len(os.Args) > 1 {
		switch os.Args[1] {
		case "auth":
			nmxx := config.AppConfig.CFNMXX
			yyjs := config.AppConfig.YYJSWIFI

			ssid := wifi.GetCurrentSSID()
			log.Infoln("当前Wi-Fi: " + ssid)
			var result string
			if containsSsid([]string{config.SsidYyjs5g, config.SsidYyjs24g}, ssid) {
				result, err = core.LoginYYJSWIFI(yyjs.Username, yyjs.Password)
			} else if containsSsid([]string{config.SsidNmxx}, ssid) {
				result, err = core.LoginNMXX(nmxx.Username, nmxx.Password)
			} else {
				log.Fatalln("当前非校园网Wi-Fi，无法认证。")
				return
			}

			if err != nil {
				sendNotification(ssid, err.Error())
				log.Fatalln(err)
			}

			log.Infoln(result)
			sendNotification(ssid, result)

		case "clean":
			log.Infoln("删除计划任务...")
			tasker, err := win_bridge.NewTasker()
			if err != nil {
				log.Fatalln(errors.WithMessage(err, "初始化任务管理器"))
			}

			err = tasker.DeleteFolder()
			if err != nil {
				log.Fatalln(err)
			}
		}

		return
	}

	// Create application with options
	err = wails.Run(&options.App{
		Title:  "校园网工具 - jing1233@qq.com",
		Width:  550,
		Height: 450,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: &options.RGBA{R: 255, G: 255, B: 255, A: 255},
		OnStartup:        app.startup,
		Bind: []interface{}{
			app,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}

func sendNotification(ssid, content string) {
	if !config.AppConfig.NotificationEnabled {
		return
	}

	err := toast.Push(content, toast.WithTitle("校园网认证: "+ssid),
		toast.WithAppID("Microsoft.Windows.Shell.RunDialog"),
		toast.WithIconRaw(appIcon),
		toast.WithAudio(toast.Default))
	if err != nil {
		log.Println(err)
	}
}
